package cn.xspace.library.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.xspace.android.imcommon.interfaces.ImServiceConnection;
import com.xspace.android.xafcommon.appliction.BaseApplication;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.QueryInitialDataBean;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.BaseRProxy;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.ExpUtils;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.PreferencesUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;

import java.util.HashMap;
import java.util.Map;

import cn.xspace.library.R;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.BuildCache;
import cn.xspace.library.util.MyInfoUtil;

/**
 * @version V1.0.0
 * @ClassName: LoginActivity
 * @author:qbluo
 * @Date：2013-6-27
 * @Description: 登陆界面
 */
public class LoginAct extends BaseActivity /*implements ILoginListener, SendRequestListener*/ {

    public static final String TAG = LoginAct.class.getSimpleName();

    private TextView deptTextView;
    private EditText mUsernameEdtTxt;
    private EditText mPasswordEdtTxt;
    private TextView forgetPasswordTextView;
    private Button mBtLogIn;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initFindViewById() {
        deptTextView = (TextView) findViewById(R.id.textview_dept_name);
        deptTextView.setText(BuildCache.getAppConfigBean(mContext).appInfo.app_deptname);
        mUsernameEdtTxt = (EditText) findViewById(R.id.edittext_phone);
        mPasswordEdtTxt = (EditText) findViewById(R.id.edittext_password);
        forgetPasswordTextView = (TextView) findViewById(R.id.tv_password_forget);
        mBtLogIn = (Button) findViewById(R.id.button_login);
    }

    @Override
    protected void initData() {
        String userName = PreferencesUtils.getPfValue(Constants.ACCOUNT_USER_MOBILE);
        mUsernameEdtTxt.setText(userName);
        String pwd = PreferencesUtils.getPfValue(Constants.ACCOUNT_PASSWORD_KEY);
        mPasswordEdtTxt.setText(pwd);
    }

    @Override
    protected void initEvent() {
        UserNameTextWatcher userWatcher = new UserNameTextWatcher();
//        mUsernameEdtTxt.addTextChangedListener(userWatcher);
        NotEmptyTextWatcher mTextWatcher = new NotEmptyTextWatcher();
        mPasswordEdtTxt.addTextChangedListener(mTextWatcher);
        forgetPasswordTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                AlertDialog.Builder passwordConfirm = new AlertDialog.Builder(mContext);
//                passwordConfirm.setTitle(R.string.initial_password_login)
//                        .setMessage(R.string.contact_password_update)
//                        .setPositiveButton(R.string.return_login, null)
//                        .show();
                Intent intent = new Intent(mContext, FindPwdActivity.class);
                startActivity(intent);
            }
        });
        mBtLogIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkData()) {
                    ImServiceConnection.stop();
                    ImServiceConnection.init(BaseApplication.mInstance, BaseRProxy.IM_SERVICE_NAME);
                    login();
                }
            }
        });
    }

    private boolean checkData() {
        String usernameForm = mUsernameEdtTxt.getText().toString().trim();
        final String username = usernameForm.replaceAll(" ", "");
        final String password = mPasswordEdtTxt.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
//            mUsernameEdtTxt.setError();
            T.showSingleL(getString(R.string.loginact_username_edtTxt_error_not_empty));
            return false;
        }
        if (!ExpUtils.validatePhone(username)) {
            T.showSingleL(getString(R.string.loginact_username_edtTxt_not_mobile_error));
//            mUsernameEdtTxt.setError(getString(RProxy.loginact_username_edtTxt_not_mobile_error));
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            T.showSingleL(getString(R.string.loginact_password_edtTxt_error_not_empty));
//            mUsernameEdtTxt.setError(getString(RProxy.loginact_password_edtTxt_error_not_empty));
            return false;
        }
        return true;
    }

    public void login() {
        showWaitDialog(R.string.loginact_prodlg_waiting_login_hint);
        String usernameForm = mUsernameEdtTxt.getText().toString().trim();
        final String username = usernameForm.replaceAll(" ", "");
        final String password = mPasswordEdtTxt.getText().toString().trim();
        final Map<String, Object> dataMap = new HashMap<>();
        //新参数
        dataMap.put("user_mobile", username);
        dataMap.put("user_pwd", AppUtils.MD5(password, false));
        dataMap.put("app_id", MyInfoUtil.getAppId(mContext));
        BldNavigation.commonLogin(mContext, dataMap, new BldNavigation.ILogInListener() {
            @Override
            public void onLogInError(Context mContext, Throwable e) {
                hideWaitDialog();
                if ("010201".equals(e.getMessage())) {
                    T.showSingleL("用户不存在或者密码不正确，请重新输入");
                } else if ("010109".equals(e.getMessage())) {
                    T.showSingleL("用户已经停用");
                } else {
                    T.showSingleL("网络异常");
                }
            }

            @Override
            public void onLogInSuccess(Context mContext, QueryInitialDataBean result) {
                PreferencesUtils.setPfValue(Constants.ACCOUNT_VALIDATED, "1");
                PreferencesUtils.setPfValue(Constants.ACCOUNT_PASSWORD_KEY, password);
                PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_MOBILE, username);
//                preLogInSuccess(username, password, result);
                BldNavigation.loginSuccess(mContext, result, false);
            }
        });
    }

    public void register(View view) {
        Intent intent = new Intent(mContext, RegisterActivity.class);
        startActivity(intent);
    }

    private void preLogInSuccess(final String userName, final String passWord, final QueryInitialDataBean returnRes) {
        if (isInitialPassword(passWord)) {
            if (!PreferencesUtils.getBooleanData(Constants.INITIAL_PASSWORD_WARN + userName)) {
                DialogHelp.getConfirmDialog(mContext,
                        mContext.getResources().getString(R.string.login_success),
                        mContext.getResources().getString(R.string.intial_password_warn),
                        mContext.getResources().getString(R.string.not_warn),
                        mContext.getResources().getString(R.string.know),
                        new ButtonClickListener() {
                            @Override
                            public void buttonClick(View view) {
                                BldNavigation.loginSuccess(mContext, returnRes, false);
                                PreferencesUtils.SaveBooleanData(Constants.INITIAL_PASSWORD_WARN + userName, true);
                            }
                        },
                        new ButtonClickListener() {
                            @Override
                            public void buttonClick(View view) {
                                BldNavigation.loginSuccess(mContext, returnRes, false);
                            }
                        }
                ).show();
            } else {
                BldNavigation.loginSuccess(mContext, returnRes, false);
            }
        } else {
            BldNavigation.loginSuccess(mContext, returnRes, false);
        }
    }

    /**
     * 判断是否为初始密码123456
     */
    private boolean isInitialPassword(String password) {
        return "123456".equals(password);
    }

    @Override
    protected boolean isShouldHideKeyboard(View v, MotionEvent event) {
        return false;
    }

    /**
     * 键盘观察者，观察EditText的变化，已对登录按钮进行改变
     */
    private class UserNameTextWatcher implements TextWatcher {
        int beforeTextLength = 0;
        int onTextLength = 0;
        boolean isChanged = false;

        int location = 0;// 记录光标的位置
        private char[] tempChar;
        private StringBuffer buffer = new StringBuffer();
        int konggeNumberB = 0;

        /**
         * Constructor.
         */
        UserNameTextWatcher() {
        }


        @Override

        public void afterTextChanged(Editable s) {
            if (isChanged) {
                location = mUsernameEdtTxt.getSelectionEnd();
                int index = 0;
                while (index < buffer.length()) {
                    if (buffer.charAt(index) == ' ') {
                        buffer.deleteCharAt(index);
                    } else {
                        index++;
                    }
                }

                index = 0;
                int konggeNumberC = 0;
                while (index < buffer.length()) {
                    if ((index == 3 || index == 8)) {
                        buffer.insert(index, ' ');
                        konggeNumberC++;
                    }
                    index++;
                }

                if (konggeNumberC > konggeNumberB) {
                    location += (konggeNumberC - konggeNumberB);
                }

                tempChar = new char[buffer.length()];
                buffer.getChars(0, buffer.length(), tempChar, 0);
                String str = buffer.toString();
                if (location > str.length()) {
                    location = str.length();
                } else if (location < 0) {
                    location = 0;
                }

                mUsernameEdtTxt.setText(str);
                Editable etable = mUsernameEdtTxt.getText();
                Selection.setSelection(etable, location);
                isChanged = false;
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            beforeTextLength = s.length();
            if (buffer.length() > 0) {
                buffer.delete(0, buffer.length());
            }
            konggeNumberB = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == ' ') {
                    konggeNumberB++;
                }
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            onTextLength = s.length();
            buffer.append(s.toString());
            if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
                isChanged = false;
                return;
            }
            isChanged = true;
        }
    }

    private class NotEmptyTextWatcher implements TextWatcher {

        /**
         * Constructor.
         */
        NotEmptyTextWatcher() {
        }

        @Override
        public void afterTextChanged(Editable s) {
            boolean enable = !(TextUtils.isEmpty(mUsernameEdtTxt.getText()) ||
                    TextUtils.isEmpty(mPasswordEdtTxt.getText()));
            mBtLogIn.setEnabled(enable);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

    }

    private long mBackPressedTime;

    @Override
    public void onBackPressed() {
        LogUtil.d("wubaojie>>>onBackPressed: ");
        long curTime = SystemClock.uptimeMillis();
        if ((curTime - mBackPressedTime) < (3 * 1000)) {
            finish();
        } else {
            mBackPressedTime = curTime;
            T.showSingleL(getString(R.string.exit_confirm));
        }
    }
}